const { log } = require('console')
const Mysql = require('./mysql.js')
const mysql = new Mysql
const request = require('./request')
const $ = new request()
const fs = require('fs')
const config = JSON.parse(fs.readFileSync('./config/config.json', 'utf-8'))
const User = JSON.parse(fs.readFileSync('./config/user.json', 'utf-8'))
const crypto = require('crypto')
const moment = require('moment')


const url = config.baserUrl
module.exports = class {
    constructor() {
    }
    async Sql(sql) {
        const result = await mysql.execMysql(sql)
        return result
    }
    // 生成卡密
    uuid() {
        const chars = crypto.randomBytes(16).toString('hex');
        const uuid = `${chars.slice(0, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}-${chars.slice(16, 20)}-${chars.slice(20)}`;
        return uuid;
    }
    // 查询卡密
    async checkCard(card) {
        const sql = `select * from sky_cash_card where token='${card}'`
        return await this.Sql(sql)

    }
    // 查询订单
    async checkOrder(oid) {
        const sql = `select * from sky_order where id=${oid}`
        return await this.Sql(sql)
    }
    // 查询兑换卡商品
    async checkCardGoods(card) {
        const option = {
            url: `${url}main.php?act=GoodsData`,
            form: { Token: card }
        }
        const result = await $.post(option)
        return result
    }
    // 兑换商品
    async exchangeGoods(card, input) {
        const option = {
            url: `${url}main.php?act=Ordersubmit&Token=${card}`,
            form: input
        }
        const result = await $.post(option)
        return result
    }
    // 用户登录
    async login(username, password) {
        // 从config获取用户名和密码
        const user = User.username
        const pass = User.password
        if (username == user && password == pass) {
            return true
        }
        return false
    }
    // 获取卡密数量
    async getCardNum() {
        const sql = `SELECT COUNT(*) as total,(SELECT COUNT(*) FROM sky_cash_card WHERE state = 2) as used, (SELECT COUNT(*) FROM sky_cash_card WHERE state = 1) as unused FROM sky_cash_card;`
        const result = await this.Sql(sql)
        return result[0]
    }
    // 获取卡密
    async getCardList(type, gid, token) {
        let sql
        // 如果token存在则只查询当前卡密
        if (token && token != '') {
            sql = `select * from sky_cash_card where token='${token}'`
            const result = await this.Sql(sql)
            return result
        }

        // 如果gid存在，则根据type查询指定商品的卡密，否则查询所有卡密
        if (gid && gid != '') {
            switch (type) {
                case "all":
                    sql = `select * from sky_cash_card where gid=${gid}`
                    break
                case "used":
                    sql = `select * from sky_cash_card where state=2 and gid=${gid}`
                    break
                case "unused":
                    sql = `select * from sky_cash_card where state=1 and gid=${gid}`
                    break
            }
        } else {
            switch (type) {
                case "all":
                    sql = `select * from sky_cash_card`
                    break
                case "used":
                    sql = `select * from sky_cash_card where state=2`
                    break
                case "unused":
                    sql = `select * from sky_cash_card where state=1`
                    break
            }
        }
        const result = await this.Sql(sql)
        return result
    }
    // 删除卡密
    async delCard(id) {
        const sql = `delete from sky_cash_card where id=${id}`
        const result = await this.Sql(sql)
        return result
    }
    // 批量删除卡密 ids是个数组
    async delCardList(ids) {
        const sql = `delete from sky_cash_card where id in (${ids.join(',')})`
        const result = await this.Sql(sql)
        return result
    }
    // 批量添加商品卡密,卡密由uuid函数生成,并且返回卡密
    async addCardList(gid, num) {
        const cardList = []
        for (let i = 0; i < num; i++) {
            const card = this.uuid()
            cardList.push(card)
        }
        const date = moment().format('YYYY-MM-DD HH:mm:ss')
        const sql = `insert into sky_cash_card (gid,oid,token,uid,state,addtime,endtime) values ${cardList.map(item => `(${gid},-1,'${item}',-1,1,'${date}', '0000-00-00 00:00:00')`).join(',')}`
        const result = await this.Sql(sql)
        return { result, cardList }
    }
    // 判断商品是否存在
    async checkGoods(gid) {
        const sql = `select * from sky_goods where gid=${gid}`
        const result = await this.Sql(sql)
        return result[0]
    }

}